//单元格宽度，以像素为单位
var grid = 16;

// 初始位置
var x = 100;
var y = 100;

// 程序主循环
function loop() {

    // 清理画布
    context.clearRect(0, 0, canvas.width, canvas.height);
    // 绘制方块
    context.fillStyle = 'green';
    context.fillRect(x, y, grid, grid);
}

// 处理键盘按键
function onKeyDown(keyEvent) {
    // left arrow key
    if (keyEvent.key == "ArrowLeft") {
        x -= grid;
    }
    // up arrow key
    else if (keyEvent.key == "ArrowUp") {
        y -= grid;
    }
    // right arrow key
    else if (keyEvent.key == "ArrowRight") {
        x += grid;
    }
    // down arrow key
    else if (keyEvent.key == "ArrowDown") {
        y += grid;
    }
}

// 获得画布对象和上下文
var canvas = document.getElementById('game');
var context = canvas.getContext('2d');

// 设置键盘监听
document.addEventListener('keydown', onKeyDown);

// 计时器，游戏开始
var timer = setInterval(loop, 1000 / 15);
